<template>
  <!-- 输入框 -->
  <div class="mb-10">
    <el-row class="mb-10">
      <el-col :span="24">
        <el-row>
          <el-col :span="6" :xs="12">
            <el-input
              v-model.trim="username"
              placeholder="请输入用户名"
              suffix-icon="Search"
              @keyup.enter="load"
              @keyup.esc="username = ''"
            />
          </el-col>
          <el-col :span="6" :xs="12">
            <el-input
              v-model.trim="phone"
              placeholder="请输入电话"
              suffix-icon="Iphone"
              class="ml-5 mr-5"
              @keyup.enter="load"
              @keyup.esc="phone = ''"
            />
          </el-col>

          <el-col :span="4" :xs="12">
            <el-cascader
              ref="locationCascader"
              placeholder="请输入地址"
              class="ml-5"
              clearable
              filterable
              :options="options"
              v-model.trim="selectedOptionsOne"
              @change="handleChangeOne"
              @keyup.enter="load"
              @clear="myclear"
            />
          </el-col>
          <el-col :span="6" :xs="12">
            <el-button class="ml-5" type="primary" @click="load"
              >搜索</el-button
            >
            <el-button type="primary" @click="clears">重置</el-button>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
  </div>

  <!-- 按钮 -->
  <el-row class="mb-10">
    <el-col :span="24">
      <el-button type="primary" @click="handleadd"
        >新增<el-icon class="ml-5" size="20px"><CirclePlus /></el-icon
      ></el-button>
      <el-popconfirm
        width="220"
        confirm-button-text="确定"
        cancel-button-text="我再想想"
        icon="InfoFilled"
        icon-color="red"
        title="您确定批量删除这些数据吗?"
        @confirm="delBatch"
        ><template #reference>
          <el-button type="danger"
            >批量删除<el-icon class="ml-10" size="20px"><Remove /></el-icon
          ></el-button> </template
      ></el-popconfirm>
      <el-upload
        class="upload_file m-12"
        :action="'http://' + serverIp + ':9090/user/import'"
        :show-file-list="false"
        accept=".xlsx"
        :on-success="handleExcelImportSuccess"
        :on-error="handleExcelImportError"
      >
        <el-button type="primary">
          导入<el-icon class="ml-5" size="20px"><Upload /></el-icon>
        </el-button>
      </el-upload>

      <el-button type="primary" @click="exp"
        >导出<el-icon class="ml-5" size="20px"><Download /></el-icon
      ></el-button> </el-col
  ></el-row>
  <!-- 表单 -->
  <div class="user_table">
    <!--selection-change 当选择项发生变化时会触发该事件 -->
    <el-table
      :data="tableData"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="id" width="80" />
      <el-table-column prop="username" label="用户名" width="100" />
      <el-table-column prop="age" label="年龄" width="100" />
      <el-table-column prop="sex" label="性别" width="100" />

      <el-table-column prop="role" label="角色" width="100" align="center">
        <template v-slot:default="scope">
          <el-tag type="success" v-if="scope.row.role === 'ROLE_STUDENGT'"
            >学生</el-tag
          >
          <el-tag v-else-if="scope.row.role === 'ROLE_TEACHER'">老师</el-tag>
          <el-tag type="danger" v-else-if="scope.row.role === 'ROLE_ADMIN'"
            >管理员</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column prop="nickname" label="昵称" width="100" />
      <el-table-column prop="address" label="地址" width="160" />
      <el-table-column prop="email" label="邮箱" width="150" />
      <el-table-column prop="phone" label="电话" width="120" />
      <el-table-column prop="xueYuanName" label="学院" width="100" />
      <el-table-column prop="banJiName" label="班级" width="120" />
      <!-- <el-table-column prop="teacherId" label="老师" /> -->

      <el-table-column label="操作" min-width="400">
        <!-- 写法1 -->
        <template v-slot:default="scope">
          <el-button
            type="warning"
            @click="lookBanJi(scope.row.banJiList)"
            v-if="scope.row.role === 'ROLE_TEACHER'"
            >查看管理班级<el-icon class="ml-5"><Edit /></el-icon
          ></el-button>
          <el-button type="success" @click="handleEdit(scope.row)"
            >编辑<el-icon class="ml-5"><Edit /></el-icon
          ></el-button>

          <!-- 气泡确认框 删除确认框 -->
          <el-popconfirm
            width="220"
            confirm-button-text="确定"
            cancel-button-text="我再想想"
            icon="InfoFilled"
            icon-color="red"
            title="您确定删除吗?"
            @confirm="del(scope.row.id)"
          >
            <template #reference>
              <el-button type="danger"
                >删除<el-icon class="ml-5"><Delete /></el-icon
              ></el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <!-- 分页 -->
  <div class="demo-pagination-block">
    <el-pagination
      v-model:current-page="pageNum"
      v-model="pageSize"
      :page-sizes="[2, 5, 10, 20]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      :small="small"
      :disabled="disabled"
      :background="background"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>

  <!-- 编辑弹窗 -->
  <el-dialog v-model="dialogFormVisible" title="用户信息" width="30%">
    <el-form :label-width="formLabelWidth">
      <el-form-item label="用户名">
        <el-input
          v-model.trim="form.username"
          autocomplete="off"
          placeholder="请输入用户名"
        />
      </el-form-item>
      <el-form-item label="性别">
        <el-radio-group v-model="form.sex" class="ml-4">
          <el-radio label="男" size="large">男</el-radio>
          <el-radio label="女" size="large">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="角色">
        <el-select
          v-model="form.role"
          class="m-2"
          placeholder="请选择角色"
          size="large"
          clearable
        >
          <el-option
            v-for="item in roles"
            :key="item.name"
            :label="item.name"
            :value="item.flag"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="昵称">
        <el-input
          v-model.trim="form.nickname"
          autocomplete="off"
          placeholder="请输入昵称"
        />
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input
          v-model.trim="form.email"
          autocomplete="off"
          placeholder="请输入邮箱"
        />
      </el-form-item>
      <el-form-item label="电话">
        <el-input
          v-model.trim="form.phone"
          autocomplete="off"
          placeholder="请输入电话"
        />
      </el-form-item>
      <el-form-item label="地址">
        <el-cascader
          placeholder="请输入地址"
          size="large"
          :options="options"
          v-model="selectedOptions"
          @change="handleChange"
          clearable
          filterable
        >
        </el-cascader>
      </el-form-item>
      <el-form-item label="班级">
        <el-select v-model="form.banJiId" placeholder="所选班级" size="large">
          <el-option
            v-for="item in BanJiValues"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="学院">
        <el-select v-model="form.xueYuanId" placeholder="所选学院" size="large">
          <el-option
            v-for="item in academies"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="save_info"> 确认 </el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 弹窗 -->
  <el-dialog v-model="dialogBanJiFormVisible" title="班级信息" width="30%">
    <el-table :data="BanJies">
      <el-table-column prop="name" label="班级名称"></el-table-column>
    </el-table>
  </el-dialog>
</template>

<script>
import { serverIp } from '../../../public/config'

import { regionData, CodeToText, TextToCode } from 'element-china-area-data'

export default {
  // name: 'pagination-modul',
  name: 'el-tables',
  data() {
    return {
      serverIp: serverIp,
      //中国省市区级
      options: regionData, //省市区数据
      selectedOptions: [], // 选中的地区
      selectedOptionsOne: [],
      tableData: [],

      //   分页器
      pageNum: 1,
      pageSize: 10,
      small: false,
      disabled: false,
      background: false,
      total: 0,

      // 分页查询-输入框
      username: '',
      phone: '',
      address: '',
      provinceCode: '',
      cityCode: '',
      areaCode: '',
      // 弹窗
      dialogFormVisible: false,
      formLabelWidth: '80px',

      form: {
        // username: '',
        // nickname: '',
        // email: '',
        // address: '',
        // phone: '',
        // provinceCode: '',
        // cityCode: '',
        // areaCode: '',
        // //角色唯一标识
        // flag: '',
        // role: '',
      },
      // 批量删除
      multipleSelection: [],

      nickname: '',
      email: '',
      //角色唯一标识
      flag: '',
      role: '',

      //角色
      roles: [],

      //班级
      BanJies: [],
      dialogBanJiFormVisible: false,
      BanJiValues: [],

      //学院
      academies: []
    }
  },
  created() {
    // 请求分页查询的数据
    this.load()
    this.selectedOptions = [
      this.form.provinceCode,
      this.form.cityCode,
      this.form.areaCode
    ]
  },
  methods: {
    // 分页2
    handleSizeChange(pageSize) {
      console.log('页数:' + pageSize)
      this.pageSize = pageSize
      this.load()
    },
    handleCurrentChange(pageNum) {
      console.log('每页的数据：' + pageNum)
      this.pageNum = pageNum
      this.load()
    },

    // 请求分页查询的数据
    load() {
      console.log(this.tab)

      this.$http
        .get('/user/page', {
          params: {
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            username: this.username,
            nickname: this.nickname,
            phone: this.phone,
            address: this.address
          }
        })
        .then((res) => {
          console.log('分页类型' + typeof res)
          console.log(res)
          this.tableData = res.data.records
          this.total = res.data.total
        })

      this.$http.get('/role').then((res) => {
        console.log(res)
        this.roles = res.data
      })

      this.$http.get('/banji').then((res) => {
        console.log(res)
        this.BanJiValues = res.data
      })

      this.$http.get('/xueyuan').then((res) => {
        console.log(res)
        this.academies = res.data
      })
    },
    // 重置
    clears() {
      this.username = ''
      this.phone = ''
      this.selectedOptionsOne = []
      this.address = this.selectedOptionsOne
      this.load()
    },
    // 弹窗
    handleadd() {
      this.dialogFormVisible = true
      this.form = {}
    },
    // 新增数据
    save_info() {
      var b = JSON.stringify(this.form)
      if (b != '{}') {
        this.$http.post('/user', this.form).then((res) => {
          console.log(res)
          if (res.status == '200') {
            this.$message.success('保存成功')
            this.dialogFormVisible = false
            // 刷新页面数据
            this.load()
          }
        })
      } else {
        this.$message.error('保存失败')
      }
    },
    // 编辑

    handleEdit(row) {
      console.log(row)
      // 当前的值赋予到form对象中
      // row是proxy 需要转化为json
      console.log('编辑类型' + typeof row.address)
      // console.log(row.address)
      this.form = JSON.parse(JSON.stringify(row))
      console.log(this.form)
      this.handleTest(row)
      // this.handleTest(row)
      // this.form = JSON.parse(JSON.stringify(row));
      // 打开弹窗
      this.dialogFormVisible = true
    },

    // 写法1
    //班级
    lookBanJi(banji) {
      console.log(123)
      console.log(banji)
      var banjis = JSON.parse(JSON.stringify(banji))
      console.log(typeof banjis)
      this.BanJies = banji
      this.dialogBanJiFormVisible = true
    },
    // 删除
    del(id) {
      this.$http.delete('/user/' + id).then((res) => {
        console.log(res)
        if (res.data) {
          this.$message.success('删除成功')
          // 刷新页面数据
          this.load()
        } else {
          this.$message.error('删除失败')
        }
      })
    },
    // 批量删除
    handleSelectionChange(val) {
      console.log(val)
      this.multipleSelection = val
    },
    delBatch() {
      // 对象数组变成 纯id的数组
      let ids = this.multipleSelection.map((v) => v.id) //[{},{},{}]=>[1,2,3]
      console.log(ids)

      this.$http.delete('/user/del/batch', { data: ids }).then((res) => {
        console.log(res)

        if (res.data) {
          this.$message.success('批量删除成功')
          // 刷新页面数据
          this.load()
        } else {
          this.$message.error('批量删除失败')
        }
      })
    },
    // 导出文件
    exp() {
      // alert('123')
      console.log('导出文件中')
      window.open(`http://${serverIp}:9090/user/export`)
    },
    // 导入文件
    //成功
    handleExcelImportSuccess() {
      this.$message.success('导入成功')
      this.load()
    },
    //失败
    handleExcelImportError() {
      this.$message.error('导入失败')
      this.load()
    },

    myclear() {
      console.log('清理中')
    },

    //初始化省市
    handleChangeOne(value) {
      console.log(value)
      if (value != null) {
        console.log(value)
        console.log(
          CodeToText[value[0]],
          CodeToText[value[1]],
          CodeToText[value[2]]
        )
        this.provinceCode = value[0]
        this.cityCode = value[1]
        this.areaCode = value[2]
        this.address =
          CodeToText[value[0]] +
          '/' +
          CodeToText[value[1]] +
          '/' +
          CodeToText[value[2]]
        console.log('页面选择:' + this.address)
      } else {
        this.address = ''
        console.log('当前地址为空：' + this.address)
      }
    },

    //初始化省市
    handleChange(value) {
      console.log(value)
      if (value != null) {
        console.log(value)
        console.log(
          CodeToText[value[0]],
          CodeToText[value[1]],
          CodeToText[value[2]]
        )
        this.form.provinceCode = value[0]
        this.form.cityCode = value[1]
        this.form.areaCode = value[2]
        this.form.address =
          CodeToText[value[0]] +
          '/' +
          CodeToText[value[1]] +
          '/' +
          CodeToText[value[2]]
        console.log('页面选择:' + this.form.address)
      } else {
        this.form.address = ''
      }
    },
    //回显 （获取数据库的省市）
    handleTest(newdata) {
      console.log('!2313')
      console.log(newdata.address)
      if (newdata.address != '' && newdata.address != null) {
        var str = newdata.address + ''
        var index = str.indexOf('/')
        var last = str.lastIndexOf('/')
        var provinceCode = TextToCode[str.slice(0, index)].code
        var cityCode =
          TextToCode[str.slice(0, index)][str.slice(index + 1, last)].code
        var areaCode =
          TextToCode[str.slice(0, index)][str.slice(index + 1, last)][
            str.slice(last + 1)
          ].code
        this.selectedOptions = [provinceCode, cityCode, areaCode]
        console.log('数据库' + this.selectedOptions)
      } else {
        this.selectedOptions = []
        console.log('数据库为空' + this.selectedOptions)

        // this.form.address = this.selectedOptions
      }
    }
  }
}
</script>

<style lang="less" scoped>
// 分页
.demo-pagination-block {
  padding: 10px;
}
.upload_file {
  display: inline-flex;
  /deep/ .el-upload{
    display: block !important;
  }
}
// 弹窗
</style>